var loanId = $("#loan").data("id"),
    loanStatus = $("#loan").data("status"),
    upload_btn_default = '<i class="fa fa-check mr10"></i>保存材料',
    upload_btn_process = '<i class="fa fa-spin fa-spinner mr10"></i>上传中...';

$(function () {
    // 初始化图片预览弹出框
    var initPopUp = function () {
        $('.mix img.doc_img').magnificPopup({
            type: 'image',
            callbacks: {
                beforeOpen: function (e) {
                    // we add a class to body to indicate overlay is active
                    // We can use this to alter any elements such as form popups
                    // that need a higher z-index to properly display in overlays
                    $('body').addClass('mfp-bg-open');

                    // Set Magnific Animation
                    this.st.mainClass = 'mfp-zoomIn';

                    // Inform content container there is an animation
                    this.contentContainer.addClass('mfp-with-anim');
                },
                afterClose: function (e) {
                    $('body').removeClass('mfp-bg-open');
                },
                elementParse: function (item) {
                    // Function will fire for each target element
                    // "item.el" is a target DOM element (if present)
                    // "item.src" is a source that you may modify
                    item.src = item.el.data('url');
                }
            },
            removalDelay: 200 //delay removal by X to allow out-animation
        });
    };
    /**
     * 获取标的相关认证图片
     */
    var loadImages = function () {
        $.post("store/listImageByOwner", {
            ownerId: loanId,
            realm: 'LOAN'
        }, function (data) {
            if (data && data.totalSize > 0) {
                data.createTime = function () {
                    return $.format.date(new Date(this.recordTime), "yyyy/MM/dd");
                };
                data.vclass = function () {
                    return this.visible ? 'text-system' : '';
                };
                var rendered = sys.render("#imageTemplate", data);
                $("#mix-container").html(rendered);
                initPopUp();
            } else {
                $("#loading").html("尚未添加认证材料");
            }
        });
    };

    /**
     * 初始化图片上传控件
     */
    var initUploader = function () {
        var doUploadBtn = $("#doUploadBtn"), document = null;
        /**
         * 弹出文件选择框
         */
        $('#upZone').click(function () {
            $('#fileInput').click();
        });
        $('#fileInput').on("change", function (e) {
            var files = e.target.files;
            if (!files.length || !window.FileReader) {
                return; // no file selected, or no FileReader support
            }
            document = files[0];
            $("#fileName").val(document.name);
            if (/^image/.test(document.type)) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $("#imagePreview").html($('<img style="width:100%;"/>').attr('src', e.target.result));
                };
                reader.readAsDataURL(document);
            }
        });
        /**
         * 保存材料：触发上传
         */
        doUploadBtn.on("click", function () {
            if (document === null) {
                alert("尚未选择材料");
            } else {
                $('form[name=uploadForm]').trigger('submit');
            }
        });
        /**
         *  上传文件
         */
        $('form[name=uploadForm]').on('submit', function (event) {
            event.stopPropagation();
            event.preventDefault();

            var url = 'store/upload';
            var formData = new FormData();
            formData.append("file", document);
            formData.append("name", $("#fileName").val());
            formData.append("desc", $("#description").val());
            formData.append("realm", 'LOAN');
            formData.append("id", loanId);

            doUploadBtn.prop("disabled", true).html(upload_btn_process);
            $.ajax({
                url: url,
                data: formData,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (res) {
                    doUploadBtn.html(upload_btn_default).prop("disabled", false);
                    if (res.success) {
                        alert("材料上传成功！");
                        location.reload();
                    } else {
                        alert(res.message);
                    }
                }
            }).fail(function () {
                alert('材料上传失败：服务器错误');
            });
        });
    };

    var imageContainer = $("#mix-container");
    /**
     * 初始化按钮事件
     */
    var initEvents = function () {
        /**
         * 删除图片
         */
        imageContainer.on("click", ".delete-link", function (e) {
            e.stopPropagation(); 
            e.preventDefault();
            if (confirm("确定要删除材料？")) {
                var id = $(this).data("id");
                $.get("store/deleteImageById/" + id, function (res) {
                    if (res === true) {
                        alert("材料删除成功");
                        location.reload();
                    } else {
                        alert("材料删除失败");
                    }
                });
            }
        });
        /**
         * 设置图片前端可见性
         */
        imageContainer.on("click", ".visible-link", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var id = $(this).data("id"), visible = $(this).data("visible"), $this = $(this), msg = visible ? "前端不可见？" : "前端可见？";
            if (confirm("确定设置图片为" + msg)) {
                $.post("store/setImageVisible", {
                    id: id,
                    visible: visible ? false : true
                }, function (res) {
                    if (res === true) {
                        alert("设置图片可见性成功");
                        location.reload();
                    }
                });
            }
        });
    };

    var initPage = function () {
        // 更新tab状态
        $("#tab-documents").removeClass("btn-default").addClass("btn-primary");
        // 更新标的列表链接
        $(".returnLoanListLink").attr("href", "loan/list/" + loanStatus.toLowerCase());
        // 初始化文件上传控件
        initUploader();
        initEvents();
        loadImages();
    };

    // 初始化页面
    initPage();
});


